package com.gimi.cloud.jimi.commonService.common.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.commonService.common.JmConfigService;
import com.gimi.cloud.jimi.commonService.common.JmPhoneMsgService;
import com.gimi.cloud.jimi.dto.sys.AlidayuDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * Created by shazhiwei on 2018/1/19.
 */
@Service
public class JmPhoneMsgServiceImpl implements JmPhoneMsgService {

    private final JmConfigService jmConfigService;

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    private static final Logger logger = LoggerFactory.getLogger(JmPhoneMsgServiceImpl.class);

    public JmPhoneMsgServiceImpl(JmConfigService jmConfigService){
        this.jmConfigService = jmConfigService;
    }

    /*@Override
    public String sendByAliDaYu(AlidayuDTO dto) {
        String result = "";
        if(StringUtils.isAnyBlank(dto.getPhone()) || null == dto){//
            return "alidayuDTO不能为空";
        }
        logger.info("===>发送参数：" + JsonUtil.toJson(dto));
        String alidayuConfig = jmConfigService.getValueByKey("alidayu");
        AlidayuDTO config = JsonUtil.jsonToBean(alidayuConfig, AlidayuDTO.class);
        String url = config.getUrl();
        String key = config.getAccessKeyId();
        String secret = config.getAccessKeySecret();
        String smsSignName = config.getSign();
        String params = dto.getParams();
        TaobaoClient client = new DefaultTaobaoClient(url, key, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName(smsSignName);//短信签名，传入的短信签名必须是在阿里大于“管理中心-短信签名管理”中的可用签名。如“阿里大于”已在短信签名管理中通过审核，则可传入”阿里大于“（传参时去掉引号）作为短信签名。短信效果示例：【阿里大于】欢迎使用阿里大于服务。
        req.setSmsParamString(params);
        req.setRecNum(dto.getPhone());
        req.setSmsTemplateCode(dto.getTemplate());
        try {
            AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
            String res = String.valueOf(rsp.getBody());
            if(CommonUtil.isJson(res)){
                JSONObject jsonObj = JSON.parseObject(res);//转化为json对象
                if(jsonObj.containsKey("alibaba_aliqin_fc_sms_num_send_response")){//发送成功
                    jsonObj = jsonObj.getJSONObject("alibaba_aliqin_fc_sms_num_send_response").getJSONObject("result");
                    logger.info("===>发送成功，" + jsonObj.toJSONString());
                    if("true".equals(jsonObj.getString("success"))){
                        return "ok";
                    }
                }else if(jsonObj.containsKey("error_response")){//发送失败
                    result = String.valueOf(jsonObj.getJSONObject("error_response"));
                }

            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return result;
    }*/

    public String sendMsgByAliYun(AlidayuDTO alidayuDto) throws ClientException {
        String result = "error";
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        String alidayuConfig = jmConfigService.getValueByKey("alidayu");
        AlidayuDTO config = JsonUtil.jsonToBean(alidayuConfig, AlidayuDTO.class);

        //初始化acsClient,暂不支持region化
        String accessKeyId = config.getAccessKeyId();
        String accessKeySecret = config.getAccessKeySecret();;
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(alidayuDto.getPhone());//必填:待发送手机号18880443285
        request.setSignName(config.getSign());//必填:短信签名-可在短信控制台中找到 给米钱包
        request.setTemplateCode(alidayuDto.getTemplate());//必填:短信模板-可在短信控制台中找到 SMS_10990892
        request.setTemplateParam(alidayuDto.getParams());//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 "{\"name\":\"Tom\", \"code\":\"123\"}"

        //request.setSmsUpExtendCode("90997");//选填-上行短信扩展码(无特殊需求用户请忽略此字段)

        //request.setOutId("yourOutId");//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        SendSmsResponse sendSmsResponse = null;//hint 此处可能会抛出异常，注意catch
        try{
            sendSmsResponse = acsClient.getAcsResponse(request);
            logger.info("阿里云通信短信发送结果：" + JsonUtil.toJson(sendSmsResponse) + "\n");
            if(sendSmsResponse != null ){
                if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equalsIgnoreCase("OK")){
                    result = "ok";
                }
            }
        }catch (Exception e){
            logger.info("阿里大于短信发送异常");
            e.printStackTrace();
        }
        return result;
    }

}
